<template>
	<view class="base-info">
		<view class="card" id="scrollFlag">
			<view class="title">
				经营者信息
			</view>
			<u-form class="form" labelPosition="left" :model="formData" :rules="rules" ref="formRef">
				<view class="m-identify">
					<view class="tips">
						<uni-icons type="info" size="14" color="#ffc30f"></uni-icons>
						<text class="desc">所有图片上传限制在2M以内。</text>
					</view>
					<view class="identify">
						<view class="name" @click="previewImg(imgHost+'/static/images/example/identify.jpg')">
							证件照 <view class="more">
								查看示例<uni-icons type="right"></uni-icons>
							</view>
						</view>
						<view class="upload">
							<uni-file-picker v-model="idCardFont" file-mediatype="image" mode="grid"
								:image-styles="imageStyles" :file-extname="extname" :auto-upload="false" custom-btn
								:limit="1" @select="selectFile($event, 1)" @delete="removeOk($event, 1)">
								<view class="custom-upload" slot="addBtn">
									<uni-icons type="camera-filled" size="52" color="#999"></uni-icons>
									<text class="label">身份证正面</text>
								</view>
							</uni-file-picker>

							<uni-file-picker v-model="idCardback" file-mediatype="image" mode="grid"
								:image-styles="imageStyles" :file-extname="extname" :auto-upload="false" custom-btn
								:limit="1" @select="selectFile($event, 2)" @delete="removeOk($event, 2)">
								<view class="custom-upload" slot="addBtn">
									<uni-icons type="camera-filled" size="52" color="#999"></uni-icons>
									<text class="label">身份证背面</text>
								</view>
							</uni-file-picker>
						</view>
					</view>
					<view class="name" v-if="formData.base_info.merchant_type == 1">
						手持身份证
					</view>
					<view class="upload" v-if="formData.base_info.merchant_type == 1">
						<uni-file-picker v-model="handIdcard" file-mediatype="image" mode="grid"
							:image-styles="imageStyles" :file-extname="extname" :auto-upload="false" custom-btn
							:limit="1" @select="selectFile($event, 3)" @delete="removeOk($event, 3)">
							<view class="custom-upload" slot="addBtn">
								<uni-icons type="camera-filled" size="52" color="#999"></uni-icons>
								<text class="label">手持身份证</text>
							</view>
						</uni-file-picker>
						<view class="example-img" @click="previewImg(imgHost+'/static/images/example/m-identify.jpg')">
							<image mode="withFix" width="100%" height="100%"
								:src="imgHost+'/static/images/example/m-identify.jpg'"></image>
							<view class="label">手持身份证示例图</view>
						</view>
					</view>

					<u-form-item class="form-item" label="姓名" labelWidth="80">
						<u-input border="bottom" :clearable="true" v-model="formData.legal_person.legal_name"
							placeholder="请输入姓名"></u-input>
					</u-form-item>
					<u-form-item class="form-item" label="身份证号" labelWidth="80">
						<u-input border="bottom" :clearable="true" v-model="formData.legal_person.legal_num"
							placeholder="请输入身份证号"></u-input>
					</u-form-item>

					<u-form-item class="form-item" label="居住地" labelWidth="80">
						<u-textarea border="bottom" :clearable="true" placeholder="请填写居住地"
							v-model="formData.legal_person.legal_address"></u-textarea>
					</u-form-item>
				</view>
				<u-form-item class="form-item" label="有效期" labelWidth="80">
					<view class="choose-time">
						<input v-model="formData.legal_person.legal_idcard_begin_date" type="text"
							placeholder="请选择起始时间">
						至
						<input v-model="formData.legal_person.legal_idcard_end_date" type="text" placeholder="请选择结束时间">
					</view>
				</u-form-item>

				<view class="card">
					<view class="title">
						营业资质
					</view>
					<view class="license">
						<view class="name">
							营业执照
						</view>

						<view class="upload">
							<uni-file-picker v-model="license" file-mediatype="image" mode="grid"
								:image-styles="imageStyles" :file-extname="extname" :auto-upload="false" custom-btn
								:limit="1" @select="selectFile($event, 4)" @delete="removeOk($event, 4)">
								<view class="custom-upload" slot="addBtn">
									<uni-icons type="camera-filled" size="52" color="#999"></uni-icons>
									<text class="label">营业执照</text>
								</view>
							</uni-file-picker>
							<view class="example-img" @click="previewImg(imgHost+'/static/images/example/license.png')">
								<image mode="withFix" width="100%" height="100%"
									:src="imgHost+'/static/images/example/license.png'"></image>
								<view class="label">营业执照示例图</view>
							</view>
						</view>
					</view>

					<u-form-item class="form-item" label="注册号" labelWidth="80">
						<u-input border="bottom" :clearable="true" v-model="formData.license_info.license_code"
							disabledColor="transparent" placeholder="请填写统一社会信用代码"></u-input>
					</u-form-item>
					<u-form-item class="form-item" label="营业执照名称" labelWidth="100">
						<u-input border="bottom" :clearable="true" v-model="formData.license_info.license_name"
							disabledColor="transparent" placeholder="请填写营业执照名称"></u-input>
					</u-form-item>
					<view class="tips">
						<uni-icons type="info" size="14" color="#ffc30f"></uni-icons>
						<text class="desc">若营业执照上无名称，请填写”个体户XXX“(XXX为营业执照上经营着姓名)</text>
					</view>

					<u-form-item class="form-item" label="注册地址" labelWidth="100">
						<u-textarea border="bottom" :clearable="true" v-model="formData.license_info.license_address"
							disabledColor="transparent" placeholder="请填写营业执照注册地址"></u-textarea>
					</u-form-item>

					<u-form-item class="form-item" label="营业起始期限" labelWidth="100">
						<view class="choose-time1">
							<input type="text" placeholder="请选择起始时间" v-model="formData.license_info.license_begin_date">
						</view>
					</u-form-item>

					<u-form-item class="form-item" label="是否是长期" labelWidth="100">
						<view class="choose-time1">
							<u-radio-group v-model="formData.license_info.license_validity_type"
								@change="groupLongChange">
								<u-radio v-for="(item,index) in is_long" :key="index" :name="item.value"
									:label="item.name" :disabled="item.disabled"></u-radio>
							</u-radio-group>
						</view>
					</u-form-item>

					<u-form-item class="form-item" label="营业结束期限" labelWidth="100"
						v-if="formData.license_info.license_validity_type == 0">
						<view class="choose-time1">
							<input type="text" placeholder="请选择结束时间" v-model="formData.license_info.license_end_date">
						</view>
					</u-form-item>
				</view>
			</u-form>
		</view>

		<view class="opt-btn">
			<button type="success" @click="stepHandle(backStep, 'back')">上一步</button>
			<button type="primary" @click="stepHandle(nextStep, 'next')">下一步</button>
		</view>
	</view>
</template>

<script setup>
	import request from '@/utils/request';
	import cache from '@/utils/cache';
	import util from '@/utils/util';
	import {
		onMounted,
		reactive,
		toRefs,
		defineProps,
		ref
	} from 'vue';

	defineOptions({
		name: 'base-info'
	});

	onMounted(() => {
		console.log('组件已挂载');
		// 这里可以执行需要在DOM挂载后执行的代码
		if (props.formData.legal_person.legal_idcard_front_photo) {
			state.idCardFont = [{
				name: props.formData.legal_person.legal_idcard_front_photo,
				extname: 'image', // 文件类型，image/video/file
				url: state.imgHost + props.formData.legal_person.legal_idcard_front_photo,
			}];
			// shibieCard(props.formData.legal_person.legal_idcard_front_photo, 1);
		}
		if (props.formData.legal_person.legal_idcard_back_photo) {
			state.idCardback = [{
				name: props.formData.legal_person.legal_idcard_back_photo,
				extname: 'image',
				url: state.imgHost + props.formData.legal_person.legal_idcard_back_photo,
			}];
			// shibieCard(props.formData.legal_person.legal_idcard_back_photo, 2);
		}
		if (props.formData.legal_person.hand_hold_idcard_photo) {
			state.handIdcard = [{
				name: props.formData.legal_person.hand_hold_idcard_photo,
				extname: 'image',
				url: state.imgHost + props.formData.legal_person.hand_hold_idcard_photo,
			}];
		}
		if (props.formData.license_info.license_photo) {
			state.license = [{
				name: props.formData.license_info.license_photo,
				extname: 'image',
				url: state.imgHost + props.formData.license_info.license_photo,
			}];
			// shibieCard(props.formData.license_info.license_photo, 4);
		}
	});

	const props = defineProps({
		backStep: 0,
		nextStep: 2,
		formData: {
			type: Object,
			default () {
				return {
					// 经营者信息
					legal_person: {
						legal_name: "", // M 法人姓名
						legal_num: "", // M 法人身份证号
						legal_address: "", // 身份证上的居住地
						legal_idcard_front_photo: "", // M法人身份证正面
						legal_idcard_back_photo: "", // M法人身份证反面
						hand_hold_idcard_photo: "", //O 手持身份证照(小微必须上送)
						legal_idcard_begin_date: "", // M法人身份证有效期开始日期
						legal_idcard_end_date: "", // M法人身份证有效期结束日期
						legal_idcard_validity_type: 0, ////经营者身份证是否长期有效，0短期，1长期
					},

					// 营业执照
					license_info: {
						license_code: "", // C 营业执照注册号
						license_name: "", // C 营业执照名称
						license_address: "", // C 营业执照注册地址 
						license_photo: "", // C 营业执照照片
						license_begin_date: "", // C 营业执照注册号开始日期
						license_end_date: "", // C 营业执照注册结束日期
						license_validity_type: 0, // C 营业执照是否长期：0否，1是
					},
				}
			}
		}
	});

	const state = reactive({
		themeColor: cache.get('themeColor'),
		imgHost: util.requestUrl(),

		idCardFont: [], // 身份证正面
		idCardback: [], // 身份证反面
		handIdcard: [], //手持身份证
		license: [], //营业执照
		earaPicker: false, // 地区弹窗
		area: [], // 地区列表

		is_long: [{
				value: 0,
				name: '否',
				disabled: false
			},
			{
				value: 1,
				name: '是',
				disabled: false
			},
		],
	});

	const rules = ref([]);
	const formRef = ref();
	const extname = ref('jpg,jpeg,png,bmp,gif,tif,svg,webp');
	const imageStyles = ref({
		"width": '316rpx', // 边框宽度
		"height": '260rpx', // 边框高度
		"border": { // 如果为 Boolean 值，可以控制边框显示与否
			"color": "#909193", // 边框颜色
			"width": "1px", // 边框宽度
			"style": "solid", // 边框样式
		}
	});
	const startData = ref('2025-01-01');
	const emits = defineEmits(["changeStep", "update:formData"]);

	// 下一步
	function stepHandle(step, type) {
		if (type == 'back') {
			console.log('上一步', step);
			emits('changeStep', step);
		} else {
			console.log('下一步', step);
			// 验证数据
			let check = checkData();
			if (!check) {
				return;
			}
			emits('update:formData', props.formData);
			emits('changeStep', step);
		}
	}

	function checkData() {
		if (!props.formData.legal_person.legal_idcard_front_photo) {
			util.showTip('请上传身份证正面');
			return false;
		}
		if (!props.formData.legal_person.legal_idcard_back_photo) {
			util.showTip('请上传身份证反面');
			return false;
		}
		if (!props.formData.license_info.license_photo) {
			util.showTip('请上传营业执照');
			return false;
		}
		return true;
	}

	// 是否长期有效
	function groupLongChange(res) {
		console.log('是否长期有效', res);
		setTimeout(() => {
			props.formData.license_info.license_validity_type = res.detail.value;
		}, 200)
	}

	// 选择图片
	function selectFile(res, flag) {
		console.log('selectFile', res, flag);

		// 上传
		for (let i = 0; i < res.tempFilePaths.length; i++) {
			upload(res.tempFilePaths[i], flag);
		}
	}

	// 删除照片
	function removeOk(res, flag) {
		console.log('removeOk', res, flag);
		// 身份证正面
		if (flag == 1) {
			props.formData.legal_person.legal_idcard_front_photo = "";
			state.idCardFont = [];
		}

		// 身份证反面
		if (flag == 2) {
			props.formData.legal_person.legal_idcard_back_photo = "";
			state.idCardback = [];
		}
		// 手持身份证
		if (flag == 3) {
			props.formData.legal_person.hand_hold_idcard_photo = "";
			state.handIdcard = [];
		}
		// 营业执照
		if (flag == 4) {
			props.formData.license_info.license_photo = "";
			state.license = [];
		}
	}

	// 图片上传:bankCard,idCard,license,store,other
	function upload(file, flag) {
		let type = 'other';
		// 身份证正面，反面，手持
		if (flag == 1) {
			type = "idCardFront";
		} else if (flag == 2) {
			type = "idCardBack";
		} else if (flag == 3) {
			type = "personWithIdCard";
		}
		// 营业执照
		else if (flag == 4) {
			type = "license";
		}
		// 银行卡正面
		else if (flag == 6) {
			type = "bankCard";
		} else {
			type = "other";
		}
		uni.uploadFile({
			url: util.requestUrl() + '/api/upload/uploadfile', // 开发者服务器接口地址
			filePath: file, // 要上传文件资源的路径
			name: 'file', // 文件对应的 key
			formData: {
				'type': type,
				'token': cache.get('M_LOGIN_TOKEN', false) || '',
				'role': cache.get('role', false) || 0,
			}, // 请求的 form data
			success: (res) => {
				const json = JSON.parse(res.data);
				if (json.code == 1) {
					const data = json.data;
					console.log('上传成功', data);
					util.showTip(data.originalName + '上传成功');
					// 处理上传成功的结果
					// 身份证正面
					if (flag == 1) {
						props.formData.legal_person.legal_idcard_front_photo = data.url;
						state.idCardFont = [{
							name: data.url,
							extname: data.fileType, // 文件类型，image/video/file
							url: data.url2,
						}];
					}

					// 身份证反面
					if (flag == 2) {
						props.formData.legal_person.legal_idcard_back_photo = data.url;
						state.idCardback = [{
							name: data.url,
							extname: data.fileType,
							url: data.url2,
						}];
					}

					// 手持身份证
					if (flag == 3) {
						props.formData.legal_person.hand_hold_idcard_photo = data.url;
						state.handIdcard = [{
							name: data.url,
							extname: data.fileType,
							url: data.url2,
						}];
					}

					// 营业执照
					if (flag == 4) {
						props.formData.license_info.license_photo = data.url;
						state.license = [{
							name: data.url,
							extname: data.fileType,
							url: data.url2,
						}];
					}

					// 识别证件
					shibieCard(data.url, flag);
				}
			},
			fail: (error) => {
				console.error('上传失败', error);
				// 处理上传失败的错误
				uni.showToast({
					title: '网络错误，请稍后再试！',
					icon: fail,
					duration: 2000
				})
			}
		});
	}

	// 识别身份证，营业执照
	function shibieCard(file, flag) {
		let params = {};
		params.file = file;
		params.cardType = 0;
		params.side = "";

		// 正面
		if (flag == 1) {
			params.cardType = 2;
			params.side = "front";
		}
		// 反面
		else if (flag == 2) {
			params.cardType = 3;
			params.side = "back";
		}
		// 营业执照
		else if (flag == 4) {
			params.cardType = 2008;
		} else {
			params.cardType = 0;
		}
		if (!params.cardType) {
			emits('update:formData', props.formData);
			return;
		}

		let methods = "juheapi/doImg"; // 请求接口
		if (params.cardType) {
			uni.showLoading({
				title: "识别中...."
			})
			request.post(methods, params)
				.then(res => {
					uni.hideLoading();

					// 身份证正面
					if (flag == 1 || flag == 2) {
						doIdcard(res, flag);
					}

					// 营业执照
					if (flag == 4) {
						doLicene(res);
					}
					emits('update:formData', props.formData);
				})
				.catch(err => {
					uni.hideLoading();
					uni.showToast({
						title: err.msg,
						icon: 'error',
						mask: true,
					})
				})
		}
	}

	// 处理身份证：1正面，2反面
	function doIdcard(res, flag = 1) {
		if (flag == 1) {
			props.formData.legal_person.legal_name = res.data.姓名;
			props.formData.legal_person.legal_num = res.data.公民身份号码;
			props.formData.legal_person.legal_address = res.data.住址;
		}
		if (flag == 2) {
			props.formData.legal_person.legal_idcard_begin_date = res.data.签发日期;
			props.formData.legal_person.legal_idcard_end_date = res.data.有效期至;
			if (res.data.有效期至 == '长期') {
				props.formData.legal_person.legal_idcard_validity_type = 1;
			} else {
				props.formData.legal_person.legal_idcard_validity_type = 0;
			}
		}
	}

	// 处理营业执照
	function doLicene(res) {
		props.formData.license_info.license_code = res.data.license_code;
		props.formData.license_info.license_name = res.data.license_name;
		props.formData.license_info.license_address = res.data.license_address;
		props.formData.license_info.license_begin_date = res.data.license_time_start;
		props.formData.license_info.license_validity_type = res.data.license_time_long;
		props.formData.license_info.license_end_date = res.data.license_time_end;
	}

	// 图片预览
	function previewImg(url) {
		uni.previewImage({
			urls: [url]
		})
	}

	function pageRoute(url) {
		uni.navigateTo({
			url
		});
	};

	function pageTabRoute(url) {
		uni.reLaunch({
			url
		});
	};

	const {
		themeColor,
		imgHost,
		idCardFont,
		idCardback,
		handIdcard,
		license,
		earaPicker,
		area,
		is_long,
	} = toRefs(state);
</script>

<style lang="scss">
	.base-info {
		.card {
			margin: 24rpx 0;
			padding: 0 24rpx;
			background-color: #fff;
			border-radius: 16rpx;

			.title {
				display: flex;
				align-items: center;
				height: 90rpx;
				font-size: $font-32;
				color: #303133;
			}

			.license,
			.m-identify,
			.identify {
				.name {
					@include f-between;
					height: 80rpx;
					color: #303133;
					line-height: 80rpx;

					.more {
						@include f-center;
						font-size: $font-24;
						color: #909193
					}
				}
			}

			.tips {
				@include f-between;
				padding: 24rpx 0;
				border-bottom: 1rpx solid #dadbde;

				.desc {
					flex: 1;
					margin-left: 8rpx;
					color: #ffc30f;
					font-size: $font-20;
				}

				.more {
					@include f-center;
					font-size: $font-20;
					color: #909193;
				}
			}

			.choose-time {
				display: flex;
				align-items: center;
				padding: 20rpx 0 24rpx;
				border-bottom: 1rpx solid #dadbde;

				input {
					text-align: center;
					font-size: $font-26;
				}
			}

			.choose-time1 {
				display: flex;
				align-items: center;
				padding: 20rpx 0 24rpx;
				border-bottom: 1rpx solid #dadbde;

				input {
					text-align: center;
					font-size: $font-26;
				}
			}
		}

		.opt-btn {
			display: flex;
			flex-direction: row;
			justify-content: space-around
		}
	}

	.upload {
		@include f-between;

		.u-list-item {
			margin: 0;
		}

		.custom-upload,
		.example-img {
			overflow: hidden;
			width: 316rpx;
			height: 260rpx;
			background-color: #f3f4f6;
			border-radius: 12rpx;
		}

		.custom-upload {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;

			.label {
				margin-top: 12rpx;
				font-size: $font-26;
				color: #909193;
			}
		}

		.example-img {
			position: relative;

			.label {
				@include f-center;
				position: absolute;
				bottom: 0;
				left: 0;
				width: 100%;
				height: 60rpx;
				background-color: rgba(0, 0, 0, 0.5);
				color: #fff;
				font-size: $font-26;
			}
		}
	}
</style>